package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"gitee.com/cjianwen/go/socks/v2"
)

type UserData struct {
	Tokent int
	Name   string
	Id     int
}

type PackData = socks.DefPackData
type ConnClient = socks.ConnClient[PackData, UserData]

func prckPack(conn *ConnClient, pack *PackData) {
	fmt.Printf("client recv %d: %s\n", pack.Head.Cmd, string(pack.Data))
}

func main() {
	// 创建一个消息接收器， 消息接收器需要一个创建消息头的回调函数
	msgReceiver := socks.NewMsgReceiver(socks.NewDefPackHelper(binary.LittleEndian), UserData{}, binary.LittleEndian)

	msgReceiver.OnConnect = func(conn *socks.ConnClient[socks.DefPackData, UserData]) {
		fmt.Println("connect to server ok!")
	}

	msgReceiver.OnDisconnect = func(conn *socks.ConnClient[socks.DefPackData, UserData]) {
		fmt.Println("disconnect from server: ", conn.RemoteAddr())
	}

	msgClient := msgReceiver.ConnectTo("127.0.0.1:6688")

	ticker := time.NewTicker(time.Millisecond * 5000)

	var pack PackData
	for {
		select {
		case <-ticker.C:
			sendClient := msgClient.GetConn()
			if sendClient != nil {
				for i := 1; i < 5; i++ {
					fmt.Printf("client send test %d \n", i)
					pack.Head.Cmd = uint32(i)
					pack.Data = []byte(fmt.Sprintf("client send test %d", i))
					sendClient.SendPack(&pack)
				}
			}
		default:
			msgReceiver.HandlePacks(prckPack)
		}

		time.Sleep(time.Millisecond * 10)
	}
}
